package com.zxx.yuanze.ocp;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

import com.zxx.yuanze.srp.answer.ImageCache;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  * 开闭原则
 *  * Open Close Principle
 * （但是SD卡缓存 与 内存缓存 只能用其一）
 * @author zqq on 2020/3/13.
 */
public class ImageLoader {

    //内存缓存
    ImageCache mImageCache = new ImageCache();

    //SD卡缓存
    DiskCache mDiskCache = new DiskCache();
    boolean isUseDisCache = false;  //是否用SD缓存

    //线程池，线程数为CPU数量
    ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());


    /**
     * （但是SD卡缓存 与 内存缓存 只能用其一）
     * @param useDisCache true:用SD卡缓存，false不用
     */
    public void setUseDisCache(boolean useDisCache) {
        isUseDisCache = useDisCache;
    }

    //
    public void displayImage(final String url, final ImageView imageView) {
        Bitmap bitmap = isUseDisCache ? mDiskCache.get(url) : mImageCache.get(url);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
            return;
        }
        imageView.setTag(url);

        service.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = downloadImage(url);
                if (bitmap == null) {
                    return;
                }
                if (imageView.getTag().equals(url)) {
                    imageView.setImageBitmap(bitmap);
                }

                mImageCache.put(url, bitmap);
            }
        });
    }

    //
    public Bitmap downloadImage(String imgUrl) {
        Bitmap bitmap = null;

        try {
            URL url = new URL(imgUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            bitmap = BitmapFactory.decodeStream(conn.getInputStream());

            conn.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

}
